<?php

namespace Shared\LocalSyntaxSpecific;

/**
 * 
 * @author Jordan Minchev <j.minchev@object.bg>
 * @copyright (c) 2014, ASPECT.BG Ltd.
 */
class EventSubscriber implements \Doctrine\Common\EventSubscriber {

    public function getSubscribedEvents() {
        return array('onFlush');
    }

    public function onFlush($Event) {
        $LocaleContentManager = \Shared\Application::instance()->getLocaleContentManager();

        $UnitOfWork = $Event->getEntityManager()->getUnitOfWork();
        
        $newEntities = $UnitOfWork->getScheduledEntityInsertions();
        foreach($newEntities as $Entity){
             if ($Entity instanceof \Shared\LocalSyntaxSpecific\Entity\LocalSyntaxSpecificI) {
                $LocaleContentManager->fix($Entity);
                $Event->getEntityManager()->persist($Entity);
                $classMetadata = $Event->getEntityManager()->getMetadataFactory()->getMetadataFor(\Doctrine\Common\Util\ClassUtils::getRealClass(get_class($Entity)));
                $UnitOfWork->recomputeSingleEntityChangeSet($classMetadata, $Entity);
            }
        }
        
        $entities = $UnitOfWork->getScheduledEntityUpdates();
        foreach ($entities as $Entity) {
            if ($Entity instanceof \Shared\LocalSyntaxSpecific\Entity\LocalSyntaxSpecificI) {
                $LocaleContentManager->fix($Entity);
            }
        }
    }

}
